package com.fawkes.project.example.common.listener;


import com.fawkes.core.constants.QueueConstants;
import com.fawkes.core.utils.StringPool;
import com.fawkes.core.utils.jackson.JsonTool;
import com.fawkes.project.example.common.constants.FormConstants;
import com.fawkes.stream.msg.send.bpm.BpmTaskEventMsg;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 通用流程任务监听
 * @author li_y29
 * @date 2021-11-04
 */
@Slf4j
@Component
public class TaskEventListener implements SmartApplicationListener {

    @Resource
    private ConnectionFactory connectionFactory;

    @Bean
    public Queue taskEventQueue() {
        return new Queue(BPM_TASK_EVENT_QUEUE);
    }

    /**
     * 创建服务自己的队列
     */
    private static final String BPM_TASK_EVENT_QUEUE = QueueConstants.SysBpmQueue.SYS_BPM_TASK_EVENT_QUEUE + StringPool.DASH + FormConstants.APPLICATION_NAME;

    @RabbitListener(queues = BPM_TASK_EVENT_QUEUE)
    private void listener(byte[] bytes){
        try {
            BpmTaskEventMsg taskEventMsg = JsonTool.parse(bytes, BpmTaskEventMsg.class);
            // TODO 监听实现 判断保证是自己流程的监听
            if(taskEventMsg.getTaskKey().equals("taskKey") && taskEventMsg.getFormKey().equals("formKey")){
                // 监听业务逻辑实现
            }
        }
        catch (Exception e){
            log.error("流程任务事件监听失败:", e);
        }
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return aClass == ApplicationStartedEvent.class;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);
        try {
            log.info("流程节点事件监听队列绑定交换机");
            //实例化一个 持久化 非独占 空闲不删除 无其余参数的队列
            channel.queueDeclare(BPM_TASK_EVENT_QUEUE, true, false, false, null);
            //绑定队列和交换机
            channel.queueBind(BPM_TASK_EVENT_QUEUE, QueueConstants.SysBpmQueue.SYS_BPM_TASK_EVENT_EXCHANGE, StringPool.EMPTY);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
